#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>

pthread_cond_t cond = PTHREAD_COND_INITIALIZER; //条件变量
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; //锁

volatile int tickets = 1000;

void* threadRoutine(void* args)
{
    std::string name = static_cast<const char*>(args);
    while(true)
    {
        pthread_mutex_lock(&mutex);
        if(tickets > 0)
        {
            std::cout << name << " get a ticket: " << tickets-- << std::endl;
            usleep(1000);
        }
        else
        {
            std::cout << name << " tickets == 0" << std::endl;
            pthread_cond_wait(&cond, &mutex); //主动释放锁，阻塞线程，被唤醒时，重新申请锁
        }
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}

int main()
{
    pthread_t t1, t2, t3;
    pthread_create(&t1, nullptr, threadRoutine, (void*)"thread-1");
    pthread_create(&t2, nullptr, threadRoutine, (void*)"thread-2");
    pthread_create(&t2, nullptr, threadRoutine, (void*)"thread-3");

    sleep(5);
    while(true)
    {
        pthread_mutex_lock(&mutex);
        tickets += 100;
        pthread_mutex_unlock(&mutex);

        // pthread_cond_signal(&cond); //使cond成立，唤醒一个线程
        pthread_cond_broadcast(&cond); //使cond成立，唤醒所有线程

        sleep(5);
    }

    pthread_join(t1, nullptr);
    pthread_join(t2, nullptr);
    pthread_join(t3, nullptr);

    return 0;
}